#pragma once

#include <iostream>
#include <string>
#include <sys/select.h>
#include <memory>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;

#define NUM sizeof(fd_set) * 8

const int gdefaultfd = -1;

class SelectServer
{
public:
    SelectServer(int port) : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);

        for (int i = 0; i < NUM; i++)
        {
            _fd_array[i] = gdefaultfd;
        }

        _fd_array[0] = _listen_socket->Fd();
    }
    void Loop(fd_set& rfds)
    {
        // 清空位图
        FD_ZERO(&rfds);

        int maxfd = gdefaultfd;
        // 将listensockfd添加进rfds里
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
                continue;

            // 合法的fd
            FD_SET(_fd_array[i], &rfds);
            // 更新最大文件描述符
            if (maxfd < _fd_array[i])
                maxfd = _fd_array[i];
        }

        FD_SET(_listen_socket->Fd(), &rfds);
        struct timeval timeout = {1, 0};
        // 让select检测就绪事件
        int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
        switch (n)
        {
        case 0:
            std::cout << "time out..." << std::endl;
            break;
        case -1:
            perror("select");
            break;
        default:
            std::cout << "有事件就绪... time out:" << timeout.tv_sec << ":" << timeout.tv_usec << std::endl;
            Dispatcher(rfds);
            break;
        }
    }
    void Start()
    {
        fd_set rfds;
        _isrunning = true;
        while (_isrunning)
        {
            Loop(rfds);
        }
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        // 已就绪，可以获取新连接
        SockPtr newfd = _listen_socket->Accepter(&client);
        if (newfd->Fd() < 0)
            return;
        else
        {
            std::cout << "获取了一个新连接：" << newfd->Fd() << " client info:" << client.Addr() << std::endl;
            int pos = -1;
            for (int j = 0; j < NUM; j++)
            {
                if (_fd_array[j] == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == gdefaultfd)
            {
                // 被写满了
                LOG(LogLevel::ERROR) << "服务器满载...";
                close(newfd->Fd());
            }
            else
                _fd_array[pos] = newfd->Fd();
        }
    }
    void Recver(int who)
    {
         // 合法，就绪，普通fd
         char buffer[1024];
         ssize_t n = recv(_fd_array[who], buffer, sizeof(buffer) - 1, 0); // 不会被阻塞，因为该文件描述符已经就绪
         if (n > 0)
         {
             buffer[n] = 0;
             std::cout << "client#" << buffer << std::endl;
             // 回显读到的消息
             std::string message = "echo#";
             message += buffer;
             send(_fd_array[who], message.c_str(), message.size(), 0); // Todo
         }
         else if (n == 0)
         {
             LOG(LogLevel::DEBUG) << "客户端退出， sockfd:" << _fd_array[who];
             close(_fd_array[who]);
             _fd_array[who] = gdefaultfd;
         }
         else
         {
             LOG(LogLevel::DEBUG) << "客户端读取出错， sockfd:" << _fd_array[who];
             close(_fd_array[who]);
             _fd_array[who] = gdefaultfd;
         }
    }
    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
                continue;

            // 合法的文件描述符
            if (_fd_array[i] == _listen_socket->Fd())
            {
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    Accepter();   //获取新连接
                }
            }
            else
            {
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                   Recver(i);   //处理IO
                }
            }
        }
    }
    ~SelectServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int _fd_array[NUM];
};